package com.luotao.test.netty.jsonnio;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-30
 * Time: 01:34
 */


import com.luotao.test.netty.model.req.ReqTrade;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-29
 * Time: 20:39
 */
public class MessageClientBak {

    public static List<Channel> channelList = new ArrayList<Channel>();

    public static ChannelFactory factory = null;

    static {

        factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 8);
        ClientBootstrap bootstrap = new ClientBootstrap(factory);

        ClientMessageFactory fac = new ClientMessageFactory();

        bootstrap.setPipelineFactory(fac);

        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setOption("keepAlive", true);

        int clientCount = 2;

        for (int i = 0; i < clientCount; i++) {
            ChannelFuture cf = bootstrap.connect(new InetSocketAddress("localhost", 8080));

            channelList.add(cf.getChannel());
        }
    }

    public static void main(String[] args)throws Exception{

        ReqTrade reqTrade = new ReqTrade();
        reqTrade.setUsername("luotao");
        reqTrade.setPassword("123");
        String s = com.alibaba.fastjson.JSON.toJSONString(reqTrade);
        byte[] request = s.getBytes();
        ChannelBuffer buf = ChannelBuffers.buffer(4 + request.length);//(2)
        buf.writeInt(reqTrade.getCommand());
        buf.writeBytes(s.getBytes());
        //      channel.write(buf);

        for (int i = 0; i < 2; i++) {
//			channelList.get(0).write("client231 "+i);
            channelList.get(0).write(buf);
            ChannelFuture channelFuture = channelList.get(1).write(buf);
         //   channelList.get(0).close();
//			channelList.get(1).write("client2 "+i);
//            channelList.get(0).write(buf);
        }
//        channelList.get(1).close();



    }
}